package com.ctg.payroll2.action.cusadmin;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.sql.SQLException;
import org.apache.struts2.ServletActionContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.ctg.payroll2.bean.CsOrgchartTree;
import com.ctg.payroll2.bean.po.PbCompany;
import com.ctg.payroll2.bean.po.CsOrgchart;
import com.ctg.payroll2.bean.po.SysUser;
import com.ctg.payroll2.service.cusadmin.IOrgStructureManageService;
import com.ctg.payroll2.util.Constants;
import com.ctg.platform.util.Parse;
import com.googlecode.jsonplugin.annotations.JSON;
import com.opensymphony.xwork2.ActionSupport;

public class OrgStructureManageAction extends ActionSupport {
	private String jsonString;
	private boolean success;
	private List departList;
	private static final int CREATE = 1;
	private static final int UPDATE = 2;
	private static final int DELETE = 3;
	private CsOrgchartTree csOrgchartTree;
	private SysUser correntUser;

	
	public CsOrgchartTree getCsOrgchartTree() {
		return csOrgchartTree;
	}

	public void setCsOrgchartTree(CsOrgchartTree csOrgchartTree) {
		this.csOrgchartTree = csOrgchartTree;
	}
	
	
	
	public String OrgTreeJSON() {
		WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(ServletActionContext.getServletContext());
		IOrgStructureManageService orgStructureManageService = (IOrgStructureManageService) wac.getBean("csOrgchartService");
				
		try {
			csOrgchartTree = orgStructureManageService.getOrgTree(this.getCorrentUser().getCompanyCode());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}	
	
	public String initStructure(){
		HttpServletRequest request = ServletActionContext.getRequest();
		WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(ServletActionContext.getServletContext());
		IOrgStructureManageService orgStructureManageService = (IOrgStructureManageService) wac.getBean("csOrgchartService");
		try{
			CsOrgchart organization = (CsOrgchart) orgStructureManageService.getRootOrganization(this.getCorrentUser().getCompanyCode());			
			if(organization!=null){
				List<CsOrgchart> resultlist = orgStructureManageService.getSubOrganization(organization.getOrgchart_id());
				this.setJsonString("[{text:'" + organization.getOrgchart_name() + "',id:'" + organization.getOrgchart_id().toString()
                    + "',leaf:" + organization.getIsLeaf().toString() + ", children:[" );
				if(resultlist.size()>0){
					for(int i = 0; i < resultlist.size(); i++){
						if(i == 0){
							this.setJsonString(this.getJsonString() + "{text:'" + resultlist.get(i).getOrgchart_name() + "',id:'" + resultlist.get(i).getOrgchart_id().toString()
				                    + "',leaf:" + resultlist.get(i).getIsLeaf().toString() + "}");
						}else{
							this.setJsonString(this.getJsonString() + ",{text:'" + resultlist.get(i).getOrgchart_name() + "',id:'" + resultlist.get(i).getOrgchart_id().toString()
				                    + "',leaf:" + resultlist.get(i).getIsLeaf().toString() + "}");
						}
					}
				}
				this.setJsonString(this.getJsonString() + "]}]");
			}
			else{
				this.setJsonString("");
			}
//			System.out.println("Init.action ResponseText: "+this.getJsonString());
		}catch(Exception e){
			e.printStackTrace();
			this.setSuccess(false);
			return ERROR;
		}
		this.setSuccess(true);
		return SUCCESS;
	}
	
	public String rootOrganization(){
		HttpServletRequest request = ServletActionContext.getRequest();
		WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(ServletActionContext.getServletContext());
		IOrgStructureManageService orgStructureManageService = (IOrgStructureManageService) wac.getBean("csOrgchartService");
		try{
			//result = (CsOrgchart) orgStructureManageService.getRootOrganization(((PbCompany) request.getSession().getAttribute("pbCompany")).getCompany_code());
			CsOrgchart organization = (CsOrgchart) orgStructureManageService.getRootOrganization(this.getCorrentUser().getCompanyCode());
			if(organization!=null){
				this.setJsonString("[{text:'" + organization.getOrgchart_name() + "',id:'" + organization.getOrgchart_id().toString()
                    + "',leaf:" + organization.getIsLeaf().toString() + "}]");
			}
			else{
				this.setJsonString("");
			}
//			System.out.println("GetRootOrg.action ResponrseText: "+this.getJsonString());
		}catch(Exception e){
			e.printStackTrace();
			this.setSuccess(false);
			return ERROR;
		}
		this.setSuccess(true);
		return SUCCESS;
	}
	
	public String modifyOrganization(){
		HttpServletRequest request = ServletActionContext.getRequest();
		WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(ServletActionContext.getServletContext());
		IOrgStructureManageService orgStructureManageService = (IOrgStructureManageService) wac.getBean("csOrgchartService");
//		System.out.println("Begin edit organization...");
		Integer Operation = Parse.toInteger(request.getParameter("operation"));
		
		CsOrgchart organization = new CsOrgchart();
		organization.setCompany_code(this.getCorrentUser().getCompanyCode());
		//organization.setCompany_code(((PbCompany) request.getSession().getAttribute("pbCompany")).getCompany_code());
		organization.setOrgchart_id(Parse.toInteger(request.getParameter("org_id")));
		organization.setSuper_org_id(Parse.toInteger(request.getParameter("parentorg_id")));
		organization.setOrgchart_code(request.getParameter("org_code"));
		organization.setOrgchart_name(request.getParameter("org_name"));
		organization.setMemo(request.getParameter("org_memo"));
		organization.setIs_valid(new Integer(1));
		
		switch(Operation){
		case CREATE:
			try{
				orgStructureManageService.addOrganization(organization);
				this.setJsonString("{text:'" + organization.getOrgchart_name() + "',id:'" + organization.getOrgchart_id().toString()
	                    + "',leaf:true,org_code:'" + organization.getOrgchart_code() + "',org_memo:'" + organization.getMemo() + "'}");
				this.setSuccess(true);
				return SUCCESS;
			}catch(SQLException se){
				se.printStackTrace();
				this.setSuccess(false);
				return ERROR;
			}
		case UPDATE:
			try{
				orgStructureManageService.editOrganization(organization);
				this.setJsonString("{text:'" + organization.getOrgchart_name() + "',id:'" + organization.getOrgchart_id().toString()
	                    + "',leaf:true,org_code:'" + organization.getOrgchart_code() + "',org_memo:'" + organization.getMemo() + "'}");
				this.setSuccess(true);
				return SUCCESS;
			}catch(SQLException se){
				se.printStackTrace();
				this.setSuccess(false);
				return ERROR;
			}
		case DELETE:
			try{
				switch(orgStructureManageService.delOrganization(organization)){
				case 0:
					this.setJsonString("{text:'" + organization.getOrgchart_name() + "',id:'" + organization.getOrgchart_id().toString()+"'}");
					this.setSuccess(true);
					return SUCCESS;
				case -1:
					this.setJsonString("{message:'Current organization has valid suborganization',errcode:-1}");
					this.setSuccess(false);
//					System.out.println(this.getJsonString());
					return ERROR;
				case -2:
					this.setJsonString("{message:'Current organization has valid employee',errcode:-2}");
					this.setSuccess(false);
//					System.out.println(this.getJsonString());
					return ERROR;
				default:
					this.setJsonString("{message:'Unhandled Error',errcode:-10000}");
					this.setSuccess(false);
//					System.out.println(this.getJsonString());
					return ERROR;
				}
				
			}catch(SQLException se){
				se.printStackTrace();
				this.setSuccess(false);
				return ERROR;
			}
		default:
			this.setSuccess(false);
			this.setJsonString("{message:'Unknown Operation',errcode:-10001}");
			return SUCCESS;
		}
	}
	
	public String subOrganization(){
		HttpServletRequest request = ServletActionContext.getRequest();
		WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(ServletActionContext.getServletContext());
		IOrgStructureManageService orgStructureManageService = (IOrgStructureManageService) wac.getBean("csOrgchartService");
		try{
			List<CsOrgchart> resultlist = orgStructureManageService.getSubOrganization(Parse.toInteger(request.getParameter("node")));
			for(int i = 0; i < resultlist.size(); i++){
				if(i == 0){
					this.setJsonString("{text:'" + resultlist.get(i).getOrgchart_name() + "',id:'" + resultlist.get(i).getOrgchart_id().toString()
		                    + "',leaf:" + resultlist.get(i).getIsLeaf().toString() + "}");
				}else{
					this.setJsonString(this.getJsonString() + ",{text:'" + resultlist.get(i).getOrgchart_name() + "',id:'" + resultlist.get(i).getOrgchart_id().toString()
		                    + "',leaf:" + resultlist.get(i).getIsLeaf().toString() + "}");
				}
			}
			this.setJsonString("["+this.getJsonString()+"]");
//			System.out.println("GetSubOrg.action ResponrseText: " + this.getJsonString());
		}catch(Exception e){
			e.printStackTrace();
			this.setSuccess(false);
			return ERROR;
		}
		this.setSuccess(true);
		return SUCCESS;
	}
	
	public String organizationInfo(){
		HttpServletRequest request = ServletActionContext.getRequest();
		WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(ServletActionContext.getServletContext());
		IOrgStructureManageService orgStructureManageService = (IOrgStructureManageService) wac.getBean("csOrgchartService");
		try{
			
			CsOrgchart organization = orgStructureManageService.getOrganizationInfo(Parse.toInteger(request.getParameter("id")));
			if(organization != null){
				this.setJsonString("[{text:'" + organization.getOrgchart_name() + "',id:'" + organization.getOrgchart_id().toString()
	                    + "',leaf:" + organization.getIsLeaf().toString() + ",org_code:'" + organization.getOrgchart_code() + "',org_memo:'" + organization.getMemo() + "'}]");
			
			}
//			System.out.println("GetOrgInfo.action ResponrseText: " + this.getJsonString());
		}catch(SQLException se){
			se.printStackTrace();
			this.setSuccess(false);
			return ERROR;
		}
		this.setSuccess(true);
		return SUCCESS;
	}
	
	
	public String DepartmentArray() {
//		HttpServletRequest request = ServletActionContext.getRequest();
		WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(ServletActionContext.getServletContext());
		IOrgStructureManageService orgStructureManageService = (IOrgStructureManageService) wac.getBean("csOrgchartService");
		try {
			departList = orgStructureManageService.getSimpleCsOrg(this.getCorrentUser().getCompanyCode());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}
 

	public String getJsonString() {
		return jsonString;
	}

	public void setJsonString(String jsonString) {
		this.jsonString = jsonString;
	}

	public boolean isSuccess() {
		return success;
	}

	public void setSuccess(boolean success) {
		this.success = success;
	}

	public List getDepartList() {
		return departList;
	}

	public void setDepartList(List departList) {
		this.departList = departList;
	}

	public SysUser getCorrentUser() {
		return (SysUser) ServletActionContext.getRequest().getSession().getAttribute(Constants.CURRENT_USER);
	}

	public void setCorrentUser(SysUser correntUser) {
		this.correntUser = correntUser;
	}

}
